package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cac409club.mapper.UserMapper;
import com.example.cac409club.model.UserDO;
import com.example.constant.ResultCodeConstant;
import com.example.dto.InternalMessageDTO;
import com.example.exception.BusinessException;
import com.example.mapper.InternalMessageMapper;
import com.example.model.InternalMessageDO;
import com.example.service.InternalMessageService;
import com.example.util.EmailUtil;
import com.example.util.OTPUtil;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   站内信Service实现类
 * </p>
 * @author 34448
 */
@Service
public class InternalMessageServiceImpl extends ServiceImpl<InternalMessageMapper, InternalMessageDO> implements InternalMessageService {

    @Autowired
    private InternalMessageMapper internalMessageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailUtil emailUtil;

    @Override
    @Transactional
    public boolean sendMessage(InternalMessageDTO internalMessageDTO) {
        // 检查发送者是否存在
        UserDO sender = userMapper.selectById(internalMessageDTO.getSenderId());
        if (sender == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "发送者不存在");
        }

        // 检查接收者是否存在
        UserDO receiver = userMapper.selectById(internalMessageDTO.getReceiverId());
        if (receiver == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "接收者不存在");
        }

        InternalMessageDO messageDO = new InternalMessageDO();
        messageDO.setSenderId(internalMessageDTO.getSenderId());
        messageDO.setReceiverId(internalMessageDTO.getReceiverId());
        messageDO.setSubject(internalMessageDTO.getSubject());
        messageDO.setBody(internalMessageDTO.getBody());
        messageDO.setSendDate(new Date());
        messageDO.setReadStatus(false);
        messageDO.setCreateBy(internalMessageDTO.getSenderId());
        messageDO.setUpdateBy(internalMessageDTO.getSenderId());

        return internalMessageMapper.insert(messageDO) > 0;
    }

    @Override
    public List<InternalMessageDO> getInbox(Integer userId) {
        // 检查用户是否存在
        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "用户不存在");
        }

        QueryWrapper<InternalMessageDO> wrapper = new QueryWrapper<>();
        wrapper.eq("receiver_id", userId);
        return internalMessageMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public boolean markAsRead(Integer messageId) {
        // 检查消息是否存在
        InternalMessageDO messageDO = internalMessageMapper.selectById(messageId);
        if (messageDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "消息不存在");
        }

        messageDO.setReadStatus(true);
        messageDO.setUpdateBy(messageDO.getSenderId()); // 假设更新人为发送者
        return internalMessageMapper.updateById(messageDO) > 0;
    }

    @Override
    @Transactional
    public boolean deleteMessage(Integer messageId) {
        // 检查消息是否存在
        InternalMessageDO messageDO = internalMessageMapper.selectById(messageId);
        if (messageDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "消息不存在");
        }

        return internalMessageMapper.deleteById(messageId) > 0;
    }

    @Override
    public boolean sendNotificationEmail(Integer userId, String subject, String body) {
        // 检查用户是否存在
        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "用户不存在");
        }

        return emailUtil.sendEmail(user.getEmail(), subject, body);
    }

    @Override
    public boolean sendOTPEmail(Integer userId) {
        // 检查用户是否存在
        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "用户不存在");
        }

        String otpCode = OTPUtil.generateOTP();
        String subject = "您的OTP验证码";
        String body = "您的OTP验证码是: " + otpCode;
        boolean emailSent = emailUtil.sendEmail(user.getEmail(), subject, body);

        if (!emailSent) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "邮件发送失败");
        }

        // 这里可以存储OTP到数据库或者其他地方以便后续验证
        // TODO: 存储OTP到数据库或者其他地方
        return emailSent;
    }

    @Override
    public boolean verifyOTP(Integer userId, String otpCode) {
        // 检查用户是否存在
        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "用户不存在");
        }

        // 这里可以从数据库或者其他地方获取存储的OTP进行验证
        // TODO: 获取存储的OTP进行验证
        boolean isValid = OTPUtil.verifyOTP(otpCode); // 假设OTPUtil有验证方法

        if (!isValid) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "验证码错误");
        }

        return isValid;
    }
}